package com.example.neusoft.cook;

import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;

import com.example.neusoft.cook.base.BaseAcyivity;
import com.example.neusoft.cook.fragment.LoginFragment;
import com.example.neusoft.cook.fragment.MainFragment;

public class MainActivity extends BaseAcyivity {
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;

    private LoginFragment loginFragment;
    private MainFragment mainFragment;

    private SharedPreferences preferences;
    private final String fileName = "food";
    private final int mode = MODE_PRIVATE;//私有的，当前文件可进行读写，其他不可

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        preferences = getSharedPreferences(fileName, mode);
        fragmentManager = getSupportFragmentManager();

        boolean loginState = getLoginState();
        if (loginState) {
            showMainFragment();
            userId = getSavedUserId();//读取已经存贮的用户Id

        } else {
            showLoginFragment();

        }
    }

    private void showLoginFragment() {
        transaction = fragmentManager.beginTransaction();
        loginFragment = new LoginFragment();
        transaction.add(R.id.fragment_holder, loginFragment);
        transaction.commit();
    }

    private void showMainFragment() {
        transaction = fragmentManager.beginTransaction();
        mainFragment = new MainFragment();
        transaction.add(R.id.fragment_holder, mainFragment);
        transaction.commit();

    }

    public void replaceLoginFragment() {
        mainFragment = new MainFragment();
        transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_holder, mainFragment);
        transaction.commit();

    }


    private boolean getLoginState() {
        String userId = getSavedUserId();
        return !userId.equals("-1");
    }

    //保存登录（读）
    private String getSavedUserId() {
        String userId = preferences.getString("user_id", "-1");//读文件没有读到数据则返回-1
        return userId;
    }
    //写登录
    public void setSavedUserId(String userId){
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("user_id",userId);
        editor.commit();
    }

}
